<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>CORS</title>
</head>
<body>
  <button type="button" id="simple_send_btn">简单请求</button>
  <button type="button" id="not_simple_send_btn">非简单请求</button>
  <script>
    var request = function(options) {
      var req = new XMLHttpRequest();
      var promise = new Promise(function(res, rej) {
        req.onreadystatechange = function() {
          if (req.readyState === 4) {
            if (req.status === 200) {
              res(req.responseText);
            } else {
              rej(new Error('Request Error: status: '+ req.status));
            }
          }
        };
      });
      if (!options) options = {};
      req.open(options.method || 'GET', options.url || '', true);
      if (options.headers && typeof options.headers === 'object') {
        Object.keys(options.headers).forEach(function(key) {
          req.setRequestHeader(key, options.headers[key]);
        });
      }
      if (options.withCredentials === true) {
        req.withCredentials = true;
      }
      req.send(options.data || null);
      return promise;
    };

    document.getElementById('simple_send_btn').addEventListener('click', function() {
      request({
        url: 'http://localhost:3000/simple',
        //withCredentials: true
      }).then(function(data) {
        console.log('success: '+ data);
      }).catch(function(err) {
        console.error('error:::::::::: '+ err.message);
      });
    });

    document.getElementById('not_simple_send_btn').addEventListener('click', function() {
      request({
        url: 'http://localhost:3000/notSimple',
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
          'X-Custom-Header': 'anrin'
        },
        withCredentials: true,
        data: JSON.stringify({
          name: 'Anrin'
        })
      }).then(function(data) {
        console.log('success: '+ data);
      }).catch(function(err) {
        console.error('error:::::::::: '+ err.message);
      });
    });
  </script>
</body>
</html>